<%@ page isELIgnored="false" language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<meta charset="UTF-8" />
<title>Insert title here</title>
<script src="js/jquery.min.js"></script>
</head>
<body>
	<h1>WebSocket聊天室</h1>
	<button class="btnQuit">退出</button>  <input class="txt" type='text'  />
	<button class="btnOne">发给某人</button>
	<button class="btnAll">发所有人</button>
	<hr/>
	<div class="userlist"></div>
	
	
<script>
// 自己的ID
var uid= '${sessionScope.loginuser.uid}';
// 发给谁  -1表示群发
var to = "-1";  
var websocket;
if('WebSocket' in window){
	websocket = new WebSocket("ws://localhost:8090/chat/ws");	
}else if('MozWebSocket' in window){
	websocket = new MozWebSocket("ws://localhost:8090/chat/ws");
}
//console.log("==websocket==" + websocket);

websocket.onopen=function(e){
	console.log("websocket:已经连接");
};

//监听信息
websocket.onmessage=function(e){
	var data = JSON.parse(e.data);
	console.log("websocket:监听信息="+ e.data);
	console.log("websocket:监听信息="+ data);
	
};

//断开连接监听  可以主动分（点击关闭）， 也可能被动分（关浏览器或者服务器断开）
websocket.onclose=function(e){
	console.log("websocket:服务器断开");
};

//发送消息
function sendMsg(obj){
	var msgStr = JSON.stringify(obj);
	websocket.send(msgStr);
}

//主动关闭连接
function closeme(){
	if(websocket!=null){
		websocket.close();
		websocket = null;
	}
}

$(function(){
	$(".btnQuit").click(function(){
		closeme();
	});
	
	$(".btnAll").click(function(){
		var info = $(".txt").val();
		var messObj = {"from":uid,"to":"-1","text":info};
		sendMsg(messObj);
		console.log("sendAll ...." + info);
		
	});
	
	$(".btnOne").click(function(){
		var info = $(".txt").val();
		var messObj = {"from":uid,"to":"zhangsanid","text":info};
		sendMsg(messObj);
		console.log("sendOne ...." + info);
	});
	
});
</script>
</body>
</html>